/*
 * @Author: gk 
 * 树形下拉框
 * @Date: 2018-03-21 22:05:29 
 * @Last Modified by: txy
 * @Last Modified time: 2019-10-28 09:15:50
 * 参数 :
 *  render 函数
 *  @param $elem class等于 select-tree 组件的节点jquery对象
 *  @param value 勾选的值 用于回显示
 *  例如: <div name="aa" class="layui-form-select select-tree" settings="{'Multiple':true, 'chkboxType':'{ &quot;Y&quot;: &quot;ps&quot;, &quot;N&quot;: &quot;s&quot; }', name: 'MX_MINGC', idKey: 'RWID', pIdKey: 'SYS_PARENTID', rootPid: null ,dataurl:'/kdayun/manager/coretables/query'}"></div>
 */
layui.define(['laypage', 'layer', 'form', 'zlConfig', 'zlContext'], function (exports) {
    "use strict";
    var $ = layui.$
        , zlConfig = layui.zlConfig
        , zlContext = layui.zlContext
        , selecttree = {};
    //组件重画消息处理
    layui.event('WM_USERDEF', 'WM_DRAW', null, function (WParam) {
        if (WParam && $(WParam.elem).attr('class') && $(WParam.elem).attr('class').indexOf('select-tree') >= 0) {
            selecttree.render($(WParam.elem), WParam.value);
        }
    });
    selecttree = {
        cmpName: '',
        render: function ($elem, value) {
            var options = ($elem.attr('settings') ? eval('(' + $elem.attr('settings') + ')') : {})
                , dataurl = options.dataurl
                , datas = []
                , isMultiple = options.Multiple
                , chkboxType = eval('(' + options.chkboxType + ')')
                , defaultOptions = {
                    Multiple: false
                    , chkboxType: {}
                    , name: 'name'
                    , method: 'get'
                    , idKey: 'id'
                    , pIdKey: 'pid'
                    , rootPid: null
                    , params: '{}'
                    , dataurl: ""
                    , value: ""
                    , placeholder: "请选择"
                    , verify:""
                    , edittype:'edit'
                    , panelHeight:'auto'
                    , parentCheck:false
                };
            var cmpName = $elem.attr('name');
            options = $.extend({}, defaultOptions, options);
            if (!$elem.attr('loaded')) {
                if ($elem.length != 1) {
                    layui.error("重复或不存在的组件名称[" + $elem.attr("name") + "]");
                    return;
                }
                var isSuccess = false;
                $.ajax({
                    type: options.method
                    , async: false
                    , url: dataurl
                    , data: eval('(' + options.params + ')')
                    , dataType: 'json'
                    // , contentType: "application/json"
                    , success: function (res) {
                        if (res['state'] == 'OK') {
                            datas = res['obj'];
                            isSuccess = true;
                            $elem.attr('loaded', 1);
                        } else {
                            throw Error(res['state']);
                            isSuccess = false;
                        }
                    }
                    , error: function (e, m) {
                        throw Error(m);
                        isSuccess = false;
                    }
                });
                if (!isSuccess) { return; }
                var treeSettings = {
                    left:options.left,
                    view: {
                        dblClickExpand: false,
                        showLine: false
                    },
                    data: {
                        key: {
                            name: options.name
                        }
                        , simpleData: {
                            enable: true
                            , idKey: options.idKey
                            , pIdKey: options.pIdKey
                            , rootPid: options.rootPid
                        }
                    },
                    check: {
                        enable: false,
                        chkboxType: { "Y": "ps", "N": "s" }
                    },
                    callback: {
                        onClick: selecttree.onClick,
                        onCheck: selecttree.onCheck,
                        beforeClick: (options.parentCheck == true ? null : selecttree.beforeClick)
                    }
                };
                if (isMultiple) {
                    treeSettings.check.enable = isMultiple;
                }
                if (chkboxType !== undefined && chkboxType != null) {
                    treeSettings.check.chkboxType = chkboxType;
                }
                treeSettings.value = ((zlContext.isEmpty(value)) ? options.value : '' ? options.value : value);
                treeSettings.verify = options.verify;
                selecttree.init($elem, treeSettings, datas, options);
            } else {
                var tempvalue = ((zlContext.isEmpty(value)) ? options.value : value);
                selecttree.setValue($elem, tempvalue,options);
            }
        },
        init: function ($elem, settings, datas, options) {
            var cmpName = $elem.attr('name'),
                readonly = $elem.attr('disabled') ? 'disabled' : '',
                mouseShow = $elem.attr('disabled') ? 'not-allowed' : 'pointer',
                layVerify = $elem.attr('lay-verify'),
                html = [
                    '   <div class = "layui-select-title" >'
                    , '     <input id="' + cmpName + 'Show"' + 'type = "text" '+ readonly +' lay-verify="'+options.verify+'" placeholder = "' + options.placeholder + '" value = "" class = "layui-input" style="cursor: '+ mouseShow +'" readonly>'
                    , '     <i class= "layui-edge" ></i>'
                    , ' </div>'];
            $elem.append(html.join(''));
            $elem.parent().append([
                '   <div class="select-tree-content" style="display:none">',
                , '     <input id="' + cmpName + 'Hide" type="hidden" ' + (layVerify ? 'lay-verify=' + layVerify : '') + ' name="' + cmpName + '">'
                , '     <ul id="' + cmpName + 'Tree" class="ztree" style="margin-top:0;"></ul>'
                , ' </div>'].join(''));
            $elem.on("click", function () {
                if($(this).attr('disabled')) return
                if ($(this).parent().find(".select-tree-content").css("display") !== "none") {
                    selecttree.hideMenu()
                } else {
                    $(this).addClass("layui-form-selected");
                    var Offset = $(this).offset();
                    var width = $(this).width() - 2;
                    var left = settings.left;

                    if (left!=undefined && left!=0){
                        $(this).parent().find(".select-tree-content").css(
                        	"cssText",
                        	"left:"+left+'px!important',
                        	"height:"+ options.panelHeight
                        ).slideDown("fast");
                    }else {       
                        $(this).parent().find(".select-tree-content").css({
                            left: Offset.left+ "px!important",
                            top: Offset.top + $(this).height() + "px",
                            height: options.panelHeight,
                        }).slideDown("fast");
                    }
                    $(this).parent().find(".select-tree-content").css({
                        width: width+ "px"
                    });
                    $("body").bind("mousedown", selecttree.onBodyDown);
                }
            });
            var treeId = cmpName + "Tree";
            var treeObj = $.fn.zTree.init($("#" + treeId), settings, datas);
            selecttree.setValue($elem, settings.value,options)
        },
        setValue: function ($elem, value, options) {
            var cmpName = $elem.attr('name');
            $("#" + cmpName + "Hide").val(value);
            var treeId = cmpName + "Tree",
                treeObj = $.fn.zTree.getZTreeObj(treeId),
                nd = treeObj.getNodes(),
                datas = treeObj.transformToArray(nd);
            for (var i = 0, l = datas.length; i < l; i++) {
                treeObj.setChkDisabled(datas[i], false);
                var j = value.indexOf(datas[i][treeObj.setting.data.simpleData.idKey])
                if (j >= 0) {
                    if (treeObj.setting.check.enable && !datas[i]['checked']) {
                        datas[i]['checked'] = true
                    } else if (!treeObj.setting.check.enable) {
                        treeObj.selectNode(datas[i]);
                    }
                }else{
                    // 清空或者重新设置值的时候需要把之前勾选的置为false
                    datas[i]['checked'] = false; 
                }
                treeObj.updateNode(datas[i]);
            }
            selecttree.assignment(cmpName, treeObj.setting.check.enable ? treeObj.getCheckedNodes() : treeObj.getSelectedNodes(),options);
            if(options!=undefined && options.edittype == 'disabled'){
            	for (var i = 0, l = datas.length; i < l; i++) {
                	treeObj.setChkDisabled(datas[i], true);
                }
            }
        },
        getValue: function ($elem) {
            var cmpName = $elem.attr('name');
            return $("#" + cmpName + "Hide").val();
        },
        show: function () {
            var formHtml = "<div></div>";
        },
        beforeClick: function (treeId, treeNode) {
            var check = (treeNode && !treeNode.isParent);
            return check;
        },
        onClick: function (event, treeId, treeNode) {
            var treeObj = $.fn.zTree.getZTreeObj(treeId),
                cmpName = treeId.substring(0, treeId.length - 4);
            if(treeNode.chkDisabled == true){
            	return
            }
            if (treeObj.setting.check.enable == true) {
                treeObj.checkNode(treeNode, !treeNode.checked, false)
                selecttree.assignment(cmpName, treeObj.getCheckedNodes());
            } else {
                selecttree.assignment(cmpName, treeObj.getSelectedNodes());
                selecttree.hideMenu();
            }
        },
        onCheck: function (event, treeId, treeNode) {
            var treeObj = $.fn.zTree.getZTreeObj(treeId),
                cmpName = treeId.substring(0, treeId.length - 4);
            selecttree.assignment(cmpName, treeObj.getCheckedNodes());
        },
        hideMenu: function () {
            $(".select-tree").removeClass("layui-form-selected");
            $(".select-tree-content").fadeOut("fast");
            $("body").unbind("mousedown", selecttree.onBodyDown);
        },
        assignment: function (cmpName, datas) {
            var treeId = cmpName + "Tree";
            var names = [];
            var ids = [];
            var treeObj = $.fn.zTree.getZTreeObj(treeId);
            for (var i = 0, l = datas.length; i < l; i++) {
                names.push(datas[i][treeObj.setting.data.key.name]);
                ids.push(datas[i][treeObj.setting.data.simpleData.idKey]);
            }
            $("#" + cmpName + "Show").attr("value", names.join(','));
            $("#" + cmpName + "Show").attr("title", names.join(','));
            $("#" + cmpName + "Hide").attr("value", ids.join(','));
        },
        onBodyDown: function (event) {
            if ($(event.target).parents(".select-tree-content").html() == null) {
                selecttree.hideMenu();
            }
        }
    }
    exports('zlSelecttree', selecttree);
});